<template>
  <div>
    <form-tpl
      ref="form"
      :form-data="formData"
      :render-list="renderList"
      :sel-options="selOptions"
      :rules="rules"
      :label-width="labelWidth"
      :disabled-props="disabledProps"
      :radio-options="radioOptions"
    >
      <template v-slot:slotPark="scopedProps">
        <div v-if="parkConfig.parkData && parkConfig.parkData.length === 0" class="no-binding flex-center align-center pointer" @click="handleBinding">
          <i class="el-icon-link"></i>
          绑定
          <span style="display: none">{{ scopedProps.formData[ scopedProps.formItem.prop ] }}</span>
        </div>
        <div v-else>
          <div class="no-binding flex-center align-center pointer" @click="handleBinding">
            <i class="el-icon-link"></i>
            绑定
            <span style="display: none">{{ scopedProps.formData[ scopedProps.formItem.prop ] }}</span>
          </div>
          <div>
            <el-input
              v-model="parkNameLabel"
              type="textarea"
              :rows="5"
              placeholder=""
              readonly
            >
            </el-input>
          </div>
        </div>
      </template>
      <template v-slot:slotForm="scopedProps">
        <template v-if="formData.ruleType === 1">
          <el-row v-for="(item,index) in scopedProps.formData[ scopedProps.formItem.prop ]" :key="'enum'+index" style="margin-bottom:10px;">
            <el-col :span="11" class="flex">
              同时包月&nbsp;&nbsp;<el-input v-model="item.text" class="flex-1" placeholder="请输入车场数" type="number" />&nbsp;&nbsp; 个{{ index === 0 ? '' : '及以上' }}车场，
            </el-col>
            <el-col :span="10" class="flex">
              享受每月&nbsp;&nbsp; <el-input v-model="item.value" class="flex-1" placeholder="请输入折扣" />&nbsp;&nbsp; 折优惠，
            </el-col>
            <el-col
              class="pointer flex-center"
              :span="3"
            >
              <a v-if="(index === 0 && scopedProps.formData[ scopedProps.formItem.prop ].length === 1) || scopedProps.formData[ scopedProps.formItem.prop ].length - 1 === index" style="color:#3680FF" @click="handlePush">新增</a>
              <a v-if="index !== 0 && scopedProps.formData[ scopedProps.formItem.prop ].length - 1 === index" style="color:#FF5A5A" class="ml-10" @click="handleDel(index)">删除</a>
            </el-col>
          </el-row>
        </template>
        <template v-else-if="formData.ruleType === 2">
          <div class="flex mb-20">
            同时包月&nbsp;&nbsp;<el-input v-model="formData.amount" class="flex-1" placeholder="请输入车场数" type="number" />&nbsp;&nbsp; 个及以上车场，
          </div>
          <el-row v-for="(item,index) in scopedProps.formData[ scopedProps.formItem.prop ]" :key="'enum'+index" class="flex" style="margin-bottom:10px;">
            <div class="flex flex-1">
              &nbsp;&nbsp;&nbsp;&nbsp;享受满&nbsp;&nbsp;<el-input v-model="item.text" class="flex-1" placeholder="请输入车场数" type="number" />&nbsp;&nbsp;元，
            </div>
            <div class="flex flex-1">
              减&nbsp;&nbsp; <el-input v-model="item.value" class="flex-1" placeholder="请输入金额" />&nbsp;&nbsp; 元；
            </div>
            <div
              class="pointer end"
            >
              <a v-if="(index === 0 && scopedProps.formData[ scopedProps.formItem.prop ].length === 1) || scopedProps.formData[ scopedProps.formItem.prop ].length - 1 === index" style="color:#3680FF" @click="handlePush">新增</a>
              <a v-if="index !== 0 && scopedProps.formData[ scopedProps.formItem.prop ].length - 1 === index" style="color:#FF5A5A" class="ml-10" @click="handleDel(index)">删除</a>
            </div>
          </el-row>
        </template>
        <template v-else>
          <el-row v-for="(item,index) in scopedProps.formData[ scopedProps.formItem.prop ]" :key="'enum'+index" style="margin-bottom:10px;">
            <el-col :span="11" class="flex">
              同时包月&nbsp;&nbsp;<el-input v-model="item.text" class="flex-1" placeholder="请输入车场数" type="number" />&nbsp;&nbsp; 个{{ index === 0 ? '' : '及以上' }}车场，
            </el-col>
            <el-col :span="10" class="flex">
              减&nbsp;&nbsp; <el-input v-model="item.value" class="flex-1" placeholder="请输入金额" />&nbsp;&nbsp; 元/月，
            </el-col>
            <el-col
              class="pointer flex-center"
              :span="3"
            >
              <a v-if="(index === 0 && scopedProps.formData[ scopedProps.formItem.prop ].length === 1) || scopedProps.formData[ scopedProps.formItem.prop ].length - 1 === index" style="color:#3680FF" @click="handlePush">新增</a>
              <a v-if="index !== 0 && scopedProps.formData[ scopedProps.formItem.prop ].length - 1 === index" style="color:#FF5A5A" class="ml-10" @click="handleDel(index)">删除</a>
            </el-col>
          </el-row>
        </template>
      </template>
    </form-tpl>
    <div slot="footer" class="dialog-footer mt-30">
      <el-button size="medium" class="mr-20" type="primary" @click="formSubmit">
        保 存
      </el-button>
      <el-button size="medium" @click="cancel">
        取 消
      </el-button>
    </div>
  </div>
</template>

<script>
import { RULE_TYPE } from '@/plugins/options'
import Discounts from '@/services/discounts.js'
import Parking from '@/services/parking-list.js'
export default {
  props: {
    dialogConfig: {
      type: Object,
      default () {
        return {
          show: false,
          title: '标题',
          width: '30%',
          data: {}
        }
      }
    }
  },
  inject: ['parkConfig',],
  data () {
    return {
      labelWidth: '90px',
      formData: {
        ruleType: 1,
        ruleName: '',
        ruleDate: [],
        parkingNames: '绑定',
        remark: '',
        id: '',
        ruleContent: [
          {
            text: '',
            value: ''
          },
        ],
        amount: '' // 第二种情况 车场数量
      },
      renderList: [
        {
          type: 'radio',
          span: 24,
          label: '优惠方式',
          prop: 'ruleType',
          placeholder: '请选择优惠方式',
          change: (val) => {
            this.formData.ruleContent = [
              {
                text: '',
                value: ''
              },
            ]
          }
        },
        {
          type: 'input',
          span: 24,
          label: '套餐名称',
          prop: 'ruleName',
          placeholder: '请输入套餐名称'
        },
        {
          type: 'slotForm',
          slot: true,
          span: 24,
          label: '优惠内容',
          prop: 'ruleContent'
        },
        {
          type: 'date',
          dateType: 'datetimerange',
          span: 24,
          defaultTime: ['00:00:00',
            '23:59:59',],
          label: '套餐有效时间',
          prop: 'ruleDate'
        },
        {
          type: 'slotPark',
          slot: true,
          span: 24,
          label: '绑定车场',
          prop: 'parkingNames'
        },
        {
          type: 'input',
          span: 24,
          label: '备注',
          prop: 'remark',
          placeholder: '请输入收费规则描述'
        },
      ],
      selOptions: {
      },
      radioOptions: {
        ruleType: RULE_TYPE
      },
      rules: {
        ruleType: [
          { required: true, message: '请选择优惠方式', trigger: 'change' },
        ],
        ruleName: [
          { required: true, message: '请输入套餐名称', trigger: 'blur' },
        ],
        ruleDate: [
          { required: true, message: '请选择套餐生效时间', trigger: 'change' },
        ],
        parkingNames: [
          { required: true, message: '请选择绑定车场', trigger: 'blur' },
        ],
        ruleContent: [
          { required: true, message: '请填写优惠内容', trigger: 'blur' },
        ]
      }
    }
  },
  computed: {
    disabledProps () {
      if (this.isEidtIng) return ['ruleType',]
      return []
    },
    isAddIng () {
      const { type } = this.dialogConfig
      return type === 'add'
    },
    isEidtIng () {
      const { type } = this.dialogConfig
      return type === 'edit'
    },
    parkNameLabel () {
      return this.parkConfig.parkName.map(i => i.label).join()
    },
    parkingIds () {
      return this.parkConfig.parkName.map(i => i.id).join()
    }
  },
  watch: {
    'dialogConfig.show': {
      handler(newVal, oldVal) {
        if (newVal) {
          this.init()
        }
      },
      immediate: true
    }
  },
  methods: {
    init () {
      if (this.isEidtIng) {
        this.getParking()
        const { ruleType,ruleName, startTime, endTime, parkingNames, remark, ruleContent, id} = this.dialogConfig.data
        const parseRuleContent = JSON.parse(ruleContent)
        const ruleData = ruleType === 1 ? parseRuleContent.data.map(i => ({ text: i.amount, value: i.rate})) : (ruleType === 2
          ? parseRuleContent.data.map(i => ({ text: i.total, value: i.reduce})) : parseRuleContent.data.map(i => ({ text: i.amount, value: i.reduce}))
        )
        this.formData = {
          ruleType,
          ruleName,
          ruleDate: [startTime,
            endTime,],
          parkingNames: parkingNames || '' ,
          remark,
          ruleContent: ruleData,
          amount: ruleType === 2 ? parseRuleContent.amount : '',
          id
        }
        const parkNames = parkingNames.split(',')
        Parking.ParkingList({pageNum: 1, pageSize: 9999, isOperate: 1}).then(res => {
          const list = (res.rows || []).map(i => ({ label: i.parkName, key: i.id, disabled: false, ...i}))
          if (parkNames && parkNames.length) {
            const arr = list.filter(i => {
              if (parkNames.findIndex(v => i.parkName === v) !== -1) {
                return i
              }
            })
            this.$nextTick(() => {
              this.parkConfig.parkName = arr
              this.parkConfig.parkData = arr.map(i => i.id)
            })
          }
        })
      }
    },
    cancel () {
      this.dialogConfig.show = false
      this.parkConfig.parkName = []
      this.parkConfig.parkList = []
      this.parkConfig.parkData = []
    },
    handleBinding () {
      this.$emit('showParkTransfer')
    },
    getParking () {
      Parking.ParkingList({pageNum: 1, pageSize: 9999, isOperate: 1}).then(res => {
        this.parkConfig.parkList = (res.rows || []).map(i => ({ label: i.parkName, key: i.id, disabled: false, ...i}))
      })
    },
    handlePush() {
      this.formData.ruleContent.push({
        value: '',
        text: ''
      })
    },
    handleDel(index) {
      this.formData.ruleContent.splice(index, 1)
    },
    formSubmit () {
      if (this.parkNameLabel) {
        this.formData.parkingNames = this.parkNameLabel
      }
      this.$refs.form.validate().then(() => {
        const { ruleType,ruleName,ruleDate,remark,ruleContent,amount,id} = this.formData
        const ruleArr = ruleType === 1 ? ruleContent.map(i => ({amount: i.text, rate: i.value}))
          : (ruleType === 2 ? ruleContent.map(i => ({ total: i.text, reduce: i.value})) : ruleContent.map(i => ({ amount: i.text, reduce: i.value})))
        const payload = {
          ruleType,
          ruleName,
          startTime: ruleDate[0] || '',
          endTime: ruleDate[1] || '',
          remark,
          parkingIds: this.parkingIds || '',
          ruleContent: ruleType === 1 ? JSON.stringify({type: ruleType, data: ruleArr}) : (ruleType === 2 ? JSON.stringify({ type: ruleType, amount, data: ruleArr}) : JSON.stringify({type: ruleType, data: ruleArr})),
          id

        }
        Discounts[this.isAddIng ? 'DiscountsAdd' : 'DiscountsEdit'](payload).then(res => {
          this.$message.success(this.isAddIng ? '新增成功' : '编辑成功')
          this.dialogConfig.show = false
          this.$emit('reload')
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.mock-money{
  height: 70px;
  background: #F2F7FF;
  padding: 0 30px;
  font-size: 16px;
  color: #64738D;
  .value{
    font-size: 20px;
    font-weight: 700;
    color: #3680FF
  }
}
.no-binding{
  position: absolute;
  right: 0;
  top: -30px;
  width: 62px;
  height: 26px;
  background: #F7F9FB;
  color: #3680FF
}
.end{
  width: 70px;
}
::v-deep .el-textarea__inner::placeholder, ::v-deep .el-textarea__inner, ::v-deep .el-input__count, ::v-deep .el-input__inner {
  font-family: AlibabaPuHuiTi-R;
}
</style>

